package com.sumainfor.pc.epc.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.MoSupplierObject;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.HtmlUtil;
import com.sumainfor.common.utlis.MoSupplierObjectUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.epc.dao.BuyerManageMapper;
import com.sumainfor.pc.epc.dao.SettlementManageMapper;
import com.sumainfor.pc.epc.dao.SupplierManageMapper;
import com.sumainfor.pc.epc.feign.BaseCfoFeign;
import com.sumainfor.pc.epc.feign.Housingauditfeign;
import com.sumainfor.pc.epc.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.epc.service.SettlementManageService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @Author PuaChen
 * @Create 2018-11-23 11:05
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Log4j2
public class SettlementManageServiceImpl implements SettlementManageService {

    @Autowired
    private SupplierManageMapper supplierManageMapper;

    @Autowired
    private BuyerManageMapper buyerManageMapper;

    @Autowired
    private Housingauditfeign housingauditfeign;

    @Autowired
    private SettlementManageMapper settlementManageMapper;

    @Autowired
    private ComUtils comUtils;

    @Autowired
    private BaseCfoFeign cfoFeign;

    @Autowired
    private ZzuulFeign zzuulFeign;

    /**
     * 结算单主页列表查询显示
     *
     * @param page
     * @param params
     * @return
     */
    @Override
    public JsonResult getSettlementList(Page page, Map<String, Object> params) {
        //结算维度
        Integer type = MapUtils.getInteger(params, "type");
        //筛选条件
        String where = MapUtils.getString(params, "where");
        //是否已结清
        String state = MapUtils.getString(params, "state");

        if (Objects.equals(type, 1)) {
            //账单结算
            IPage<Map<String, Object>> pages = settlementManageMapper.selectStaMainList(page, CustomMap.create("StaType", state)
                    .put("StaCut", where));
            pages.setRecords(pages.getRecords().stream().map(ite1 -> {
                ite1.put("StaCutName", MapUtils.getString(Constants.SettlementType.TYPE_MAP, MapUtils.getString(ite1, "StaCut")));
                ite1.put("RejectCount", settlementManageMapper.getRejectRemitCount(CustomMap.create("StaId", ite1.get("StaId"))));
                //申请次数
                ite1.put("AuditCount", settlementManageMapper.getRejectRemitCount(CustomMap.create("StaId", ite1.get("StaId")).put("AllCount", "1")));
                ite1.put("type", type);
                return ite1;
            }).collect(Collectors.toList()));
            return JsonResult.success(pages);
        } else if (Objects.equals(type, 2)) {
            //供应商结算
            IPage<Map<String, Object>> response = settlementManageMapper.selectStaForSupplierList(page, CustomMap.create()
                    .put("State", state)
                    .put("SupType", where)
            );
            response.setRecords(response.getRecords().stream().map(iv2 -> {
                iv2.put("SupTypeName", ShopTypeSelectUtil.selectSupplierTypeById(MapUtils.getString(iv2, "SupType")));
                iv2.put("RejectCount", settlementManageMapper.getRejectRemitCount(CustomMap.create("SupId", iv2.get("SupId"))));
                //申请次数
                iv2.put("AuditCount", settlementManageMapper.getRejectRemitCount(CustomMap.create("SupId", iv2.get("SupId")).put("AllCount", "1")));
                iv2.put("type", type);
                return iv2;
            }).collect(Collectors.toList()));
            return JsonResult.success(response);
        }

        return JsonResult.error("类型错误");
    }


    /**
     * 查询获得结算单详情底部的列表数据
     *
     * @param params type 1 获取的是账单维度，2获取的是供应商的维度
     *               sourceId 结算单主表编号或者是供应商的编号
     *               state 供应商专用 筛选状态是否是已结算的
     * @return
     */
    @Override
    public JsonResult selectOrderInfos(Page page, Map<String, Objects> params) {
        //结算维度
        Integer type = MapUtils.getInteger(params, "type");
        //结算单主表编号或者是供应商的编号
        String sourceId = MapUtils.getString(params, "sourceId");
        //供应商专用 筛选状态是否是已结算的
        String state = MapUtils.getString(params, "state");

        if (Objects.equals(type, 1)) {
            //供应商
            return JsonResult.success(settlementManageMapper.selectStaInfoLinkSupplier(page, sourceId).getRecords().stream().map(iv -> {
                if (ShopTypeSelectUtil.isSupplierTypeIsYZ(MapUtils.getString(iv, "SupType"))) {
                    //是硬装供应商
                    //判断是否已经预算矫正
                    if (StringUtils.isBlank(MapUtils.getString(iv, "CopeWithPrice"))) {
                        //没有矫正
                        iv.put("IsCorrect", false);
                    } else {
                        //已经矫正 就不要显示 较真按钮了
                        iv.put("IsCorrect", true);
                    }
                }
                return iv;
            }).collect(Collectors.toList()));
        } else if (Objects.equals(type, 2)) {
            //账单
            IPage<Map<String, Object>> response = settlementManageMapper.selectSupplierStaInfo(page, CustomMap.create()
                    .put("SupId", sourceId)
                    .put("state", state)
            );

            //判断是否已经结清
            AtomicBoolean done = new AtomicBoolean(true);

            response.setRecords(response.getRecords().stream().map(item -> {
                //1.装修结算单,2备件结算单,3.保洁结算单,4.硬装结算单
                String staCutName = null;
                switch (MapUtils.getInteger(item, "StaCut")) {
                    case 1:
                        staCutName = "装修结算单";
                        break;
                    case 2:
                        staCutName = "备件结算单";
                        break;
                    case 3:
                        staCutName = "保洁结算单";
                        break;
                    case 4:
                        staCutName = "硬装结算单";
                        break;
                }
                item.put("StaCut", staCutName);
                if (ShopTypeSelectUtil.isSupplierTypeIsYZ(MapUtils.getString(item, "SupType"))) {
                    //是硬装供应商
                    //判断是否已经预算矫正
                    if (StringUtils.isBlank(MapUtils.getString(item, "CopeWithPrice"))) {
                        //没有矫正
                        item.put("IsCorrect", false);
                    } else {
                        //已经矫正 就不要显示 较真按钮了
                        item.put("IsCorrect", true);
                    }
                    item.put("YS", true);
                } else {
                    item.put("YS", false);
                }

                if (MapUtils.getInteger(item, "State").equals(0)) {
                    done.set(false);
                }

                return item;
            }).collect(Collectors.toList()));


            CustomMap customMap = ObjectUtil.convertObjectToMap(response);
            customMap.put("Done", done.get());
            if (CollectionUtils.isEmpty(response.getRecords())) {
                customMap.put("YS", false);
            } else {
                Object ys = response.getRecords().get(0).get("YS");
                customMap.put("YS", ys);
            }
            return JsonResult.success(customMap);
        }
        return JsonResult.error("类型错误");
    }

    /**
     * 申请打款
     * 不论是 账单维度 还是供应商的维度 只是对账单中一个供应商的详表进行的操作
     * 结算单详表中  供应商只能唯一存在一个
     *
     * @param params {
     *               SupId
     *               StaId
     *               price
     *               }
     * @return
     */
    @Override
    public JsonResult applyForMoney(Map<String, Object> params) {
        String supId = MapUtils.getString(params, "SupId");
        String staId = MapUtils.getString(params, "StaId");
        BigDecimal price = new BigDecimal(MapUtils.getString(params, "price"));

        if (price.compareTo(new BigDecimal("0")) == 0) {
            return JsonResult.error("打款为0元你想啥呢");
        }

        //获得这个供应商数据
        Map<String, Object> supData = supplierManageMapper.getSupplierOne(supId);
        if (MapUtils.isEmpty(supData)) {
            return JsonResult.error("没有这个供应商");
        }

        //供应商维度
        Map<String, Object> staMain = settlementManageMapper.getStaMainById(staId);
        if (staMain == null || staMain.isEmpty()) {
            return JsonResult.error("没有这个结算单数据");
        }

        if (MapUtils.getInteger(staMain, "StaType").equals(1)) {
            return JsonResult.error("这个结算单已结清");
        }

        //判断是否是硬装供应商
        boolean isYZ = ShopTypeSelectUtil.isSupplierTypeIsYZ(MapUtils.getString(supData, "SupType"));

        Map<String, Object> infoMap = settlementManageMapper.getApplyOrderInfoBySupId(supId, staId);
        if (MapUtils.isEmpty(infoMap)) {
            return JsonResult.error("没有找到这条数据");
        }
        //计算已支付的金额
        BigDecimal donePrice = new BigDecimal(MapUtils.getString(infoMap, "PaidPrice"));
        BigDecimal sum = new BigDecimal(MapUtils.getString(infoMap, "CopeWithPrice"));
        BigDecimal notSum = sum.subtract(donePrice);
        if (!isYZ) {
            //限制打款金额
            if (sum.compareTo(donePrice) == 0 || sum.compareTo(donePrice.add(price)) == -1) {
                return JsonResult.error("打款金额错误");
            }
            //查询申请打款次数
            //先查询总金额 申请
            BigDecimal moneyRemitSum = ObjectUtil.convertBigDecimal(settlementManageMapper.selectRemitMoneySum(MapUtils.getString(infoMap, "StaId")), "0");
            //申请打款的总金额 + 本次打款金额 比较总金额
            if (notSum.compareTo(moneyRemitSum.add(price)) == -1) {
                //计算本机需要申请的钱
                throw new TCException("申请的总金额不能超过应付金额,本次你还能打款" + notSum.subtract(moneyRemitSum) + "元");
            }
        } else {
            //判断是否已经预算矫正了
            if (StringUtils.isNotBlank(MapUtils.getString(infoMap, "CopeWithPrice"))) {
                //不为空 说明已经矫正
                //限制打款金额
                if (sum.compareTo(donePrice) == 0 || sum.compareTo(donePrice.add(price)) == -1) {
                    return JsonResult.error("打款金额错误");
                }
                //查询申请打款次数
                //先查询总金额 申请
                BigDecimal moneyRemitSum = ObjectUtil.convertBigDecimal(settlementManageMapper.selectRemitMoneySum(MapUtils.getString(infoMap, "StaId")), "0");
                //申请打款的总金额 + 本次打款金额 比较总金额
                if (notSum.compareTo(moneyRemitSum.add(price)) == -1) {
                    //计算本机需要申请的钱
                    throw new TCException("申请的总金额不能超过应付金额,本次你还能打款" + notSum.subtract(moneyRemitSum) + "元");
                }
            } else {
                //没有进行预算校正
                //打款的钱是负数 供应商欠唐巢的钱
                price = price.subtract(price.multiply(new BigDecimal(2)));
            }
        }


        //进行 打款申请的操作
        //计算未支付的金额
        BigDecimal unpaidPrice = sum.subtract(donePrice);

        String remId = comUtils.getLocalTrmSeqNumByLook("Remit", Constants.DATA_SOURCE_TCEPC, "tcepc_statement_remit", "StaRemId");

        Date payTime = DateUtils.stringToDate(MapUtils.getString(params, "PayTime"), "yyyy-MM-dd");

        //构建打款记录数据
        int row = settlementManageMapper.insertRemitData(ParamsCommon.commonInsertParms(CustomMap.create()
                        .put("StaRemId", remId)
                        .put("PayTime", payTime)
                        .put("PayPrice", price)
                        .put("StaRemNotes", MapUtils.getString(params, "StaRemNotes"))
                        .put("StasId", MapUtils.getString(infoMap, "StasId"))
                        .put("CopeWithPrice", MapUtils.getString(infoMap, "CopeWithPrice"))
                        .put("PaidPrice", donePrice)
                        .put("UnpaidPrice", unpaidPrice)
                        .put("StaId", staId)
                        .put("SupId", supId)
                        .put("RemState", 1)
                , getClass()));
        if (row <= 0) {
            return JsonResult.error("申请打款失败");
        }

        //通知
        CustomMap data = CustomMap.create("MeType", 5)
                .put("Title", "待确认打款单")
                .put("Content", HtmlUtil.stringToHTML("您有新的打款单需确认，请及时处理！；", "", Color.blue))
                .put("by", ContextUtils.getUserId())
                .put("IfJump", 1)
                .put("Neturl", "/sys-engineeringmanager/settlement")
                .put("term", 3);
        zzuulFeign.AddMessage(data);

        return JsonResult.success("成功");
    }

    /**
     * 获得查看详情的列表数据 账单明细
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult selectOrderInfo(Map<String, Objects> params) {
        String staId = MapUtils.getString(params, "StaId");
        String supId = MapUtils.getString(params, "SupId");

        Map<String, Object> staMain = settlementManageMapper.getStaMainById(staId);
        if (MapUtils.isEmpty(staMain)) {
            return JsonResult.error("没有这个结算单信息");
        }
        //判读如果是硬装结算单
        if (Objects.equals(MapUtils.getInteger(staMain, "StaCut"), 4)) {
            //查询供应商是硬装还是软装
            Map<String, Object> supplierOne = supplierManageMapper.getSupplierOne(supId);
            if (MapUtils.isEmpty(supplierOne)) {
                return JsonResult.error("没有查询到这个供应商");
            }
            if (Objects.equals(MapUtils.getInteger(supplierOne, "SupType"), 1)) {
                //是硬装供应商 查询硬装的数据
                //查询装修计划详表的信息
                List<Map<String, Object>> planList = buyerManageMapper.selectPlanInfo(MapUtils.getString(staMain, "SourceId"));
                if (planList == null || planList.isEmpty()) {
                    throw new TCException("没有查询到装修计划详情表数据");
                }
                List<String> houIds = Lists.newArrayList();
                //总价
                BigDecimal sum = new BigDecimal(0);
                List<CustomMap> dataResult = Lists.newArrayList();
                for (Map<String, Object> map : planList) {
                    sum = sum.add(new BigDecimal(MapUtils.getString(map, "SupPrice")));
                    houIds.add(MapUtils.getString(map, "HouId"));
                    dataResult.add(CustomMap.create("HouId", MapUtils.getString(map, "HouId"))
                            .put("SupPrice", MapUtils.getString(map, "SupPrice")));
                }
                log.info("调用市场部查询房源的信息 ===> {}", houIds);
                //查询房源的信息
                JsonResult<List<Map<String, Object>>> response = housingauditfeign.getProjectNameAndHousingConf(houIds);
                if (!response.isSuccess()) {
                    log.error("返回错误信息： {}", response);
                    throw new TCException("查询房源信息失败");
                }
                //数据进行拼装
                List<Map<String, Object>> result = response.getResult();
                for (CustomMap map : dataResult) {
                    for (Map<String, Object> hou : result) {
                        if (map.getToString("HouId").equals(MapUtils.getString(hou, "HouId"))) {
                            map.putAll(hou);
                        }
                    }
                }
                return JsonResult.success(CustomMap.create("sunPrice", sum)
                        .put("list", dataResult)
                        .put("orderNumber", staId)
                        .put("type", MapUtils.getString(Constants.SettlementType.TYPE_MAP, MapUtils.getString(staMain, "StaCut")))
                        .put("type2", "新房装修")
                        .put("buyerId", MapUtils.getString(planList.get(0), "PlanId"))
                );
            }
        }

        //判读如果是保洁结算单
        if (Objects.equals(MapUtils.getInteger(staMain, "StaCut"), 3)) {
            List<Map<String, Object>> restList = settlementManageMapper.selectRestList(MapUtils.getString(staMain, "SourceId"));
            if (restList == null || restList.isEmpty()) {
                throw new TCException("没有查询到其他费用的数据");
            }

            BigDecimal sum = new BigDecimal("0");

            for (int i = 0; i < restList.size(); i++) {
                Map<String, Object> map = restList.get(i);
                map.put("ComType", ShopTypeSelectUtil.selectShopTypeById(MapUtils.getString(map, "ComType")));
                sum = sum.add(ObjectUtil.convertBigDecimal(map.get("sumPrice")));

            }

            return JsonResult.success(CustomMap.create("sunPrice", sum)
                    .put("list", restList)
                    .put("orderNumber", staId)
                    .put("type", MapUtils.getString(Constants.SettlementType.TYPE_MAP, MapUtils.getString(staMain, "StaCut")))
                    .put("type2", "新房装修")
                    .put("buyerId", MapUtils.getString(staMain, "SourceId"))
            );
        }

        //普通的商品信息
        List<Map<String, Object>> buyerInfoList = settlementManageMapper.selectBuyerInfoByBuyerId(MapUtils.getString(staMain, "SourceId"), supId);
        if (buyerInfoList == null || buyerInfoList.isEmpty()) {
            throw new TCException("获取不到采购详表数据");
        }

        String buyerId = (String) buyerInfoList.get(0).get("BuyId");

        BigDecimal sum = new BigDecimal(0);
        List<CustomMap> dataResult = Lists.newArrayList();
        List<String> moIds = Lists.newArrayList();
        for (Map<String, Object> map : buyerInfoList) {
            if (MapUtils.getIntValue(staMain, "StaCut") == 1) {
                if (StringUtils.isBlank(MapUtils.getString(map, "PutStorage")) || MapUtils.getIntValue(map, "PutStorage") == 0) {
                    continue;
                }
                sum = sum.add(new BigDecimal(MapUtils.getString(map, "BuyPrice")));
                dataResult.add(CustomMap.create("sumPrice", MapUtils.getString(map, "BuyPrice"))
                        .put("PutStorage", MapUtils.getInteger(map, "PutStorage"))
                        .put("SupId", MapUtils.getString(map, "SupId"))
                        .put("ComSpeMoId", MapUtils.getString(map, "ComSpeMoId"))
                );
            } else {
                sum = sum.add(new BigDecimal(MapUtils.getString(map, "BuyPrice")));
                dataResult.add(CustomMap.create("sumPrice", MapUtils.getString(map, "BuyPrice"))
                        .put("BuyNumber", MapUtils.getInteger(map, "BuyNumber"))
                        .put("SupId", MapUtils.getString(map, "SupId"))
                        .put("ComSpeMoId", MapUtils.getString(map, "ComSpeMoId"))
                );
            }

            moIds.add(MapUtils.getString(map, "ComSpeMoId"));
        }

        List<Map<String, Object>> moList = settlementManageMapper.selectShopInfo(moIds);
        if (moList.isEmpty()) {
            throw new TCException("没有商品数据");
        }

        dataResult = dataResult.stream().filter(ObjectUtil.distinctByKey(b -> b.getToString("ComSpeMoId"))).collect(Collectors.toList());
        for (CustomMap map : dataResult) {
            for (Map<String, Object> mo : moList) {
                if (map.getToString("ComSpeMoId").equals(MapUtils.getString(mo, "ComSpeMoId"))) {

                    //相等
                    List<MoSupplierObject> supList = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(mo, "supplier"));
                    if (supList.isEmpty()) {
                        throw new TCException("没有查询到供应商的信息");
                    }
                    MoSupplierObject supOne = MoSupplierObjectUtil.selectSupplierById(supList, supId);
                    if (supOne == null) {
                        throw new TCException("没有这个供应商");
                    }
                    map.putAll(mo);
                    map.remove("supplier");
                    map.put("ComType", ShopTypeSelectUtil.selectShopTypeById(MapUtils.getString(mo, "ComType")));
                    map.put("signPrice", supOne.getPrice());
                }
            }
        }

        return JsonResult.success(CustomMap.create("sunPrice", sum)
                .put("list", dataResult)
                .put("orderNumber", staId)
                .put("type", MapUtils.getString(Constants.SettlementType.TYPE_MAP, MapUtils.getString(staMain, "StaCut")))
                .put("type2", "-")
                .put("buyerId", buyerId)
        );
    }


    /**
     * 查询申请打款记录列表
     * 必须参数 ： StaId
     *
     * @param page
     * @param params
     * @return
     */
    @Override
    public JsonResult selectApplyBillLog(Page page, Map<String, Object> params) {
        return JsonResult.success(settlementManageMapper.selectApplyBillLog(page, params));
    }

    /**
     * 查询申请打款记录 通过供应商编号查询
     *
     * @param page
     * @param params
     * @return
     */
    @Override
    public JsonResult selectApplyBillLogForSupplier(Page page, Map<String, Object> params) {
        return JsonResult.success(settlementManageMapper.selectApplyBillLogForSupplier(page, params));
    }


    /**
     * 返回 结算单账单类型 下拉框筛选条件
     *
     * @return
     */
    @Override
    public JsonResult getApplyTypeList() {
        List<CustomMap> dataList = Lists.newArrayList();
        for (Map.Entry<String, Object> entry : Constants.SettlementType.TYPE_MAP.entrySet()) {
            dataList.add(CustomMap.create("id", entry.getKey())
                    .put("name", entry.getValue()));
        }
        return JsonResult.success(dataList);
    }

    /**
     * 撤回一条 申请打款记录
     *
     * @param remId
     * @return
     */
    @Override
    public JsonResult deleteApplyRemit(String remId) {
        return settlementManageMapper.deleteRemitOne(remId) <= 0 ? JsonResult.error("这条数据不存在哦") : JsonResult.success("撤回成功");
    }


    /**
     * 预算校正
     *
     * @param stId     主结算单的编号
     * @param supId    供应商的编号
     * @param sumPrice 校正的价格
     * @return
     */
    @Override
    public JsonResult budgetRevise(String stId, String supId, BigDecimal sumPrice) {
        Map<String, Object> infoData = settlementManageMapper.getApplyOrderInfoBySupId(supId, stId);
        if (MapUtils.isEmpty(infoData)) {
            return JsonResult.error("不存在这个结算单");
        }

        Map<String, Object> supData = supplierManageMapper.getSupplierOne(supId);
        if (MapUtils.isEmpty(supData)) {
            return JsonResult.error("没有这个供应商信息");
        }

        if (!ShopTypeSelectUtil.isSupplierTypeIsYZ(MapUtils.getString(supData, "SupType"))) {
            return JsonResult.error("不是硬装供应商不能进行预算校正");
        }

        if (MapUtils.getIntValue(infoData, "CopeWithPrice", 0) != 0) {
            return JsonResult.error("预算已经校正不可再次校正");
        }

        //判断是否已经打款了
        BigDecimal unPrice = ObjectUtil.convertBigDecimal(infoData.get("UnpaidPrice"));
        BigDecimal donePrice = ObjectUtil.convertBigDecimal(infoData.get("PaidPrice"));
        CustomMap data = CustomMap.create();

        data.put("CopeWithPrice", sumPrice);
        data.put("StaId", stId);
        data.put("SupId", supId);

        if (unPrice.doubleValue() != 0) {
            //说明已经操作了
            if (unPrice.doubleValue() < 0) {
                //已经打款了 重新计算
                //判断差值
                if (sumPrice.compareTo(donePrice) == 1) {
                    //大  没完成需要继续打款
                    BigDecimal unMoney = sumPrice.subtract(donePrice);

                    data.put("UnpaidPrice", unMoney);
                    data.put("State", "0");

                } else if (sumPrice.compareTo(donePrice) == -1) {
                    //发现 小了 说明完成了  供应商欠唐巢的钱了
                    data.put("UnpaidPrice", "0");
                    data.put("State", 1);
                    anewSettlePriceState(stId);
                    //计算 欠款为多少
                    BigDecimal subVal = donePrice.subtract(sumPrice);
                    //调用财务的服务进行对款项的操作记录
                    JsonResult result = cfoFeign.updateBalancePriceBySupId(supId, subVal.toString());
                    if (!result.isSuccess()) {
                        throw new TCException(result.getErrorCode(), result.getErrorMessage());
                    }
                } else if (sumPrice.compareTo(donePrice) == 0) {
                    //相等说明完成了 互不相欠正好
                    data.put("UnpaidPrice", "0");
                    data.put("State", 1);
                    anewSettlePriceState(stId);
                }
            } else if (unPrice.doubleValue() > 0) {
                throw new TCException("数据出现未知的异常");
            }
        }

        int row = settlementManageMapper.updateStaInfoData(ParamsCommon.commonUpdateParms(data, getClass()));
        if (row <= 0) {
            //todo  需要分布式事务解决
            throw new TCException("更新出现未知的异常");
        }

        return JsonResult.success("操作成功");
    }

    /**
     * 重新统计 是否详表全部完成了 结算 之后做对应的处理操作
     *
     * @param staId
     */
    private void anewSettlePriceState(String staId) {
        int unDoneOrderCount = settlementManageMapper.getUnDoneOrderCount(staId);
        if (unDoneOrderCount == 0) {
            //更新主表的信息
            Map<String, Object> moneyData = settlementManageMapper.statisticsMoneyInfo(staId);
            if (MapUtils.getDoubleValue(moneyData, "UnpaidPrice") != 0) {
                throw new TCException("数据出现未知的错乱,请联系管理员");
            }
            int row = settlementManageMapper.updateStaMainData(ParamsCommon.commonUpdateParms(CustomMap.create()
                            .put("StaId", staId)
                            .put("StaType", 1)
                            .put("CopeWithPrices", moneyData.get("CopeWithPrice"))
                            .put("PaidPrices", moneyData.get("PaidPrice"))
                            .put("UnpaidPrices", 0)
                    , getClass()));
            if (row <= 0) {
                throw new TCException("数据修改出现异常,请联系管理员");
            }
        }
    }

}
